<template>
  <div class="media-upload">
    <div class="page-header">
      <h2>媒资上传</h2>
    </div>

    <a-row :gutter="24">
      <!-- 上传区域 -->
      <a-col :span="16">
        <a-card title="上传媒资" class="upload-card">
          <a-upload-dragger
            v-model:file-list="fileList"
            name="file"
            :multiple="true"
            :action="uploadUrl"
            :before-upload="beforeUpload"
            @change="handleChange"
            @remove="handleRemove"
          >
            <p class="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
            <p class="ant-upload-hint">
              支持单个或批量上传，严禁上传公司数据或其他敏感文件
            </p>
          </a-upload-dragger>

          <div class="upload-tips">
            <h4>上传说明：</h4>
            <ul>
              <li>支持格式：MP4、AVI、MOV、PDF、DOC、PPT、ZIP、RAR</li>
              <li>文件大小：视频文件不超过500MB，其他文件不超过100MB</li>
              <li>文件命名：建议使用英文或数字，避免特殊字符</li>
            </ul>
          </div>
        </a-card>
      </a-col>

      <!-- 上传进度 -->
      <a-col :span="8">
        <a-card title="上传进度" class="progress-card">
          <div v-if="uploadingFiles.length === 0" class="no-upload">
            <p>暂无上传任务</p>
          </div>
          <div v-else>
            <div
              v-for="file in uploadingFiles"
              :key="file.uid"
              class="upload-item"
            >
              <div class="file-info">
                <span class="filename">{{ file.name }}</span>
                <span class="size">{{ formatFileSize(file.size) }}</span>
              </div>
              <a-progress
                :percent="file.percent || 0"
                :status="file.status === 'error' ? 'exception' : undefined"
                size="small"
              />
              <div class="file-status">
                <a-tag :color="getStatusColor(file.status)">
                  {{ getStatusText(file.status) }}
                </a-tag>
              </div>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 已上传文件列表 -->
    <a-card title="已上传文件" class="file-list-card" style="margin-top: 24px">
      <a-table
        :columns="columns"
        :data-source="uploadedFiles"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'size'">
            {{ formatFileSize(record.size) }}
          </template>
          
          <template v-else-if="column.key === 'type'">
            <a-tag :color="getFileTypeColor(record.type)">
              {{ getFileTypeText(record.type) }}
            </a-tag>
          </template>
          
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="previewFile(record)">
                预览
              </a-button>
              <a-button type="link" size="small" @click="downloadFile(record)">
                下载
              </a-button>
              <a-button type="link" size="small" @click="deleteFile(record)">
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { InboxOutlined } from '@ant-design/icons-vue'

// 上传相关
const fileList = ref<any[]>([])
const uploadingFiles = ref<any[]>([])
const uploadUrl = 'https://run.mocky.io/v3/435e224c-44fb-4773-9faf-380c5e6a2188' // 模拟上传地址

// 已上传文件列表
const uploadedFiles = ref([
  {
    key: '1',
    id: 1,
    name: 'AI基础课程视频.mp4',
    type: 'video',
    size: 102400000,
    uploadTime: '2024-01-15 10:30:00',
    url: 'https://example.com/video1.mp4'
  },
  {
    key: '2',
    id: 2,
    name: '课程大纲.pdf',
    type: 'document',
    size: 2048000,
    uploadTime: '2024-01-15 09:15:00',
    url: 'https://example.com/outline.pdf'
  }
])

const loading = ref(false)

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 2,
  showSizeChanger: true,
  showQuickJumper: true
})

// 表格列定义
const columns = [
  {
    title: '文件名',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '文件类型',
    dataIndex: 'type',
    key: 'type'
  },
  {
    title: '文件大小',
    dataIndex: 'size',
    key: 'size'
  },
  {
    title: '上传时间',
    dataIndex: 'uploadTime',
    key: 'uploadTime'
  },
  {
    title: '操作',
    key: 'action',
    width: 200
  }
]

// 上传前检查
const beforeUpload = (file: any) => {
  const isValidType = checkFileType(file)
  const isValidSize = checkFileSize(file)
  
  if (!isValidType) {
    message.error('不支持的文件格式！')
    return false
  }
  
  if (!isValidSize) {
    message.error('文件大小超出限制！')
    return false
  }
  
  // 添加到上传列表
  uploadingFiles.value.push({
    uid: file.uid || Date.now(),
    name: file.name,
    size: file.size,
    percent: 0,
    status: 'uploading'
  })
  
  return true
}

// 检查文件类型
const checkFileType = (file: File) => {
  const allowedTypes = [
    'video/mp4',
    'video/avi',
    'video/mov',
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-powerpoint',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'application/zip',
    'application/x-rar-compressed'
  ]
  return allowedTypes.includes(file.type)
}

// 检查文件大小
const checkFileSize = (file: File) => {
  const maxSize = file.type.startsWith('video/') ? 500 * 1024 * 1024 : 100 * 1024 * 1024
  return file.size <= maxSize
}

// 处理上传变化
const handleChange = (info: any) => {
  const { file, fileList: newFileList } = info
  
  // 更新文件列表
  fileList.value = newFileList
  
  // 更新上传进度
  const uploadingFile = uploadingFiles.value.find(f => f.uid === file.uid)
  if (uploadingFile) {
    uploadingFile.percent = file.percent || 0
    uploadingFile.status = file.status
    
    if (file.status === 'done') {
      message.success(`${file.name} 上传成功`)
      // 添加到已上传文件列表
      uploadedFiles.value.unshift({
        key: Date.now().toString(),
        id: Date.now(),
        name: file.name,
        type: getFileTypeFromMime(file.type),
        size: file.size,
        uploadTime: new Date().toLocaleString(),
        url: file.response?.url || '#'
      })
    } else if (file.status === 'error') {
      message.error(`${file.name} 上传失败`)
    }
  }
}

// 处理文件移除
const handleRemove = (file: any) => {
  // 从上传列表中移除
  const index = uploadingFiles.value.findIndex(f => f.uid === file.uid)
  if (index > -1) {
    uploadingFiles.value.splice(index, 1)
  }
}

// 获取文件类型
const getFileTypeFromMime = (mimeType: string) => {
  if (mimeType.startsWith('video/')) return 'video'
  if (mimeType.startsWith('application/pdf')) return 'document'
  if (mimeType.includes('word') || mimeType.includes('powerpoint')) return 'document'
  if (mimeType.includes('zip') || mimeType.includes('rar')) return 'archive'
  return 'other'
}

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    uploading: 'blue',
    done: 'green',
    error: 'red'
  }
  return colorMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    uploading: '上传中',
    done: '已完成',
    error: '上传失败'
  }
  return textMap[status] || '未知'
}

// 获取文件类型颜色
const getFileTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    video: 'blue',
    document: 'green',
    archive: 'orange',
    other: 'default'
  }
  return colorMap[type] || 'default'
}

// 获取文件类型文本
const getFileTypeText = (type: string) => {
  const textMap: Record<string, string> = {
    video: '视频',
    document: '文档',
    archive: '压缩包',
    other: '其他'
  }
  return textMap[type] || '未知'
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 预览文件
const previewFile = (file: any) => {
  message.info(`预览文件：${file.name}`)
}

// 下载文件
const downloadFile = (file: any) => {
  message.success(`开始下载：${file.name}`)
}

// 删除文件
const deleteFile = (file: any) => {
  const index = uploadedFiles.value.findIndex(f => f.id === file.id)
  if (index > -1) {
    uploadedFiles.value.splice(index, 1)
    message.success('文件删除成功')
  }
}

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
}

onMounted(() => {
  // 初始化
})
</script>

<style scoped>
.media-upload {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.upload-card {
  border-radius: 8px;
}

.progress-card {
  border-radius: 8px;
}

.file-list-card {
  border-radius: 8px;
}

.upload-tips {
  margin-top: 24px;
  padding: 16px;
  background-color: #f6f8fa;
  border-radius: 6px;
}

.upload-tips h4 {
  margin: 0 0 12px 0;
  color: #333;
}

.upload-tips ul {
  margin: 0;
  padding-left: 20px;
}

.upload-tips li {
  margin-bottom: 4px;
  color: #666;
}

.no-upload {
  text-align: center;
  color: #999;
  padding: 40px 0;
}

.upload-item {
  margin-bottom: 16px;
  padding: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.file-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.filename {
  font-weight: 500;
  color: #333;
}

.size {
  color: #666;
  font-size: 12px;
}

.file-status {
  margin-top: 8px;
  text-align: right;
}

:deep(.ant-upload-drag) {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
}

:deep(.ant-upload-drag:hover) {
  border-color: #1890ff;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #fafafa;
}
</style>
